<template>
  <ContentWrap>
    <!-- 搜索 -->
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
      <el-form-item label="司机姓名" prop="nickname">
        <el-input v-model="queryParams.nickname" placeholder="请输入司机姓名" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="手机号码" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入手机号码" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="驾驶证号" prop="driverLicenseNo">
        <el-input v-model="queryParams.driverLicenseNo" placeholder="请输入驾驶证号" clearable @keyup.enter="handleQuery"
          class="!w-240px" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable class="!w-240px">
          <el-option v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="工作状态" prop="workStatus">
        <el-select v-model="queryParams.workStatus" placeholder="请选择工作状态" clearable class="!w-240px">
          <el-option label="空闲" :value="0" />
          <el-option label="工作中" :value="1" />
          <el-option label="休息" :value="2" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss" type="datetimerange"
          start-placeholder="开始日期" end-placeholder="结束日期" class="!w-240px" />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" />搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" />重置
        </el-button>
        <el-button type="primary" plain @click="openAuthForm('create')" v-hasPermi="['system:driver:create']">
          <Icon icon="ep:plus" /> 司机认证
        </el-button>
        <el-button type="warning" plain @click="handleImport" v-hasPermi="['system:driver:import']">
          <Icon icon="ep:upload" /> 导入
        </el-button>
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['system:driver:export']">
          <Icon icon="ep:download" />导出
        </el-button>
        <el-button type="danger" plain :disabled="checkedIds.length === 0" @click="handleDeleteBatch"
          v-hasPermi="['system:driver:delete']">
          <Icon icon="ep:delete" />批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <ContentWrap>
    <el-table v-loading="loading" :data="list" @selection-change="handleRowCheckboxChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="司机编号" align="center" key="id" prop="id" />
      <el-table-column label="用户名" align="center" prop="username" :show-overflow-tooltip="true" />
      <el-table-column label="司机姓名" align="center" prop="nickname" :show-overflow-tooltip="true" />
      <el-table-column label="手机号码" align="center" prop="mobile" width="120" />
      <el-table-column label="驾驶证号" align="center" prop="driverLicenseNo" width="150" />
      <el-table-column label="服务城市" align="center" prop="serviceCity" width="100" />
      <el-table-column label="状态" key="status" align="center">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="工作状态" align="center" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.workStatus === 0" type="success" size="small">
            空闲
          </el-tag>
          <el-tag v-else-if="scope.row.workStatus === 1" type="warning" size="small">
            工作中
          </el-tag>
          <el-tag v-else type="info" size="small">
            休息
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="审核时间" align="center" prop="auditTime" :formatter="dateFormatter" width="180" />
      <el-table-column label="驾驶证类型" align="center" prop="driverLicenseType" width="120" />
      <el-table-column label="操作" align="center" width="160">
        <template #default="scope">
          <div class="flex items-center justify-center">
            <el-button type="primary" link @click="openForm('update', scope.row.id)"
              v-hasPermi="['system:driver:update']">
              <Icon icon="ep:edit" />修改
            </el-button>
            <el-dropdown @command="(command) => handleCommand(command, scope.row)" v-hasPermi="[
              'system:driver:delete',
              'system:driver:update-password'
            ]">
              <el-button type="primary" link>
                <Icon icon="ep:d-arrow-right" /> 更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="handleDelete" v-if="checkPermi(['system:driver:delete'])">
                    <Icon icon="ep:delete" />删除
                  </el-dropdown-item>
                  <el-dropdown-item command="handleResetPwd" v-if="checkPermi(['system:driver:update-password'])">
                    <Icon icon="ep:key" />重置密码
                  </el-dropdown-item>
                  <el-dropdown-item command="handleDetail">
                    <Icon icon="ep:view" />查看详情
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize"
      @pagination="getList" />
  </ContentWrap>

  <!-- 添加或修改司机对话框 -->
  <DriverForm ref="formRef" @success="getList" />
  <!-- 司机认证对话框 -->
  <DriverAuthForm ref="authFormRef" @success="getList" />
  <!-- 司机详情对话框 -->
  <DriverDetail ref="detailRef" />
</template>

<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { checkPermi } from '@/utils/permission'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { CommonStatusEnum } from '@/utils/constants'
import * as DriverApi from '@/api/system/driver'
import DriverForm from './DriverForm.vue'
import DriverAuthForm from './DriverAuthForm.vue'
import DriverDetail from './DriverDetail.vue'

defineOptions({ name: 'SystemDriver' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  nickname: undefined,
  mobile: undefined,
  driverLicenseNo: undefined,
  status: undefined,
  workStatus: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await DriverApi.getDriverPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 打开司机认证表单 */
const authFormRef = ref()
const openAuthForm = (type: string, id?: number) => {
  authFormRef.value.open(type, id)
}

/** 司机导入 */
const handleImport = () => {
  message.info('导入功能开发中...')
}

/** 点击状态标签切换状态 */
const handleStatusClick = async (row: DriverApi.DriverVO) => {
  try {
    // 计算要切换到的状态
    const newStatus = row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
    const text = newStatus === CommonStatusEnum.ENABLE ? '启用' : '停用'
    const driverName = row.nickname || '该'

    // 修改状态的二次确认
    await message.confirm('确认要"' + text + '"' + driverName + '司机吗?')

    // 发起修改状态
    await DriverApi.updateDriverStatus(row.id, newStatus)

    // 刷新列表
    await getList()
  } catch {
    // 用户取消操作，不做任何处理
  }
}

/** 修改司机状态 */
const handleStatusChange = async (row: DriverApi.DriverVO) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    const driverName = row.nickname || '该'
    await message.confirm('确认要"' + text + '"' + driverName + '司机吗?')
    // 发起修改状态
    await DriverApi.updateDriverStatus(row.id, row.status)
    // 刷新列表
    await getList()
  } catch {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  }
}

/** 导出按钮操作 */
const exportLoading = ref(false)
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await DriverApi.exportDriver(queryParams)
    download.excel(data, '司机数据.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 操作分发 */
const handleCommand = (command: string, row: DriverApi.DriverVO) => {
  switch (command) {
    case 'handleDelete':
      handleDelete(row.id)
      break
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleDetail':
      handleDetail(row)
      break
    default:
      break
  }
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await DriverApi.deleteDriver(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 批量删除按钮操作 */
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (rows: DriverApi.DriverVO[]) => {
  checkedIds.value = rows.map((row) => row.id)
}

const handleDeleteBatch = async () => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起批量删除
    await DriverApi.deleteDriverList(checkedIds.value)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 重置密码 */
const handleResetPwd = async (row: DriverApi.DriverVO) => {
  try {
    // 重置的二次确认
    const driverName = row.nickname || '该司机'
    const result = await message.prompt(
      '请输入"' + driverName + '"的新密码',
      t('common.reminder')
    )
    const password = result.value
    // 发起重置
    await DriverApi.resetDriverPassword(row.id, password)
    message.success('修改成功，新密码是：' + password)
  } catch { }
}

/** 查看详情 */
const detailRef = ref()
const handleDetail = (row: DriverApi.DriverVO) => {
  detailRef.value.open(row)
}

/** 初始化 */
onMounted(() => {
  getList()
})
</script>